package com.sgcc.fj.pmos.mobileapp.activity;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.sgcc.fj.pmos.arouter.app.AppArouterPath;
import com.sgcc.fj.pmos.common.base.MvpBaseActivity;
import com.sgcc.fj.pmos.common.dialog.CommonDialog;
import com.sgcc.fj.pmos.common.utils.BurialPointUtils;
import com.sgcc.fj.pmos.common.utils.DialogUtil;
import com.sgcc.fj.pmos.common.utils.SysUtil;
import com.sgcc.fj.pmos.common.widget.MyEditText;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.fj.pmos.mobileapp.bean.MouldEditionBean;
import com.sgcc.fj.pmos.mobileapp.bean.SmsCodeBean;
import com.sgcc.fj.pmos.mobileapp.bean.VerifyExistMobileBean;
import com.sgcc.fj.pmos.mobileapp.contract.RegisteredContract;
import com.sgcc.fj.pmos.mobileapp.presenter.RegisteredPresenter;

/**
 * 注册页面和 注册成功的页面
 */
@Route(path = AppArouterPath.APP_REGISTERED)
public class RegisteredActivity extends MvpBaseActivity<RegisteredPresenter> implements RegisteredContract.View {

    private TitleBar titleBar;
    private RelativeLayout rlRegistered;
    private MyEditText etAccount;
    private MyEditText etCipher;
    private MyEditText etAgainCipher;
    private MyEditText etPhone;
    private MyEditText etCode;
    private TextView tvGetcode;
    private CheckBox checkbox;
    private TextView btnRegistered;
    private RelativeLayout rlRegisteredSuccess;
    private RelativeLayout rlPolicy;
    private TextView tvAccount;
    private TextView tvCipherError;
    private TextView tvAgainCipherError;
    private TextView tvPhone;
    private TextView btnRealNameAuth;
    private TextView btnExit;
    private TextView tvAccountError;
    private TextView tvPhoneError;
    private TextView tvPolicy;
    private TextView tvCodeError;
    private CountDownTimer timer;
    private MouldEditionBean mMouldEditionBean;

    private CheckBox cbCheckPwd, cbCheckAgainPwd;
    private ImageView ivPwdClose, ivPwdAgainClose, ivPhoneClose;

    private boolean mAccountExists;//账号已存在
    private boolean mPhoneExists;//账号已存在

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_registered;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mPresenter.queryMouldEdition();
        findViewByIds();
        setViewAction();
    }

    private void setViewAction() {
        etAccount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    String account = etAccount.getText().toString().trim();

                    if (!(account.length() >= 5 && account.length() <= 20)) {
                        setViewStatus(true, "登录账号长度在5-20位之间", tvAccountError, etAccount);
                    } else {
                        setViewStatus(false, "", tvAccountError, etAccount);
                        mPresenter.verifyExistLoginName(account);
                    }
                }
            }
        });

        etCipher.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    String cipher = etCipher.getText().toString().trim();
                    if (!(cipher.length() >= 5 && cipher.length() <= 20)) {
                        setViewStatus(true, "密码长度在5-20位之间", tvCipherError, etCipher);
                        return;
                    }
                    if (!SysUtil.isPasswordCard(cipher)) {
                        setViewStatus(true, "密码格式不正确", tvCipherError, etCipher);
                        return;
                    }
                    setViewStatus(false, "", tvCipherError, etCipher);
                }
            }
        });

        etAgainCipher.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    String againCipher = etAgainCipher.getText().toString().trim();
                    String cipher = etCipher.getText().toString().trim();

                    if (!(againCipher.length() >= 5 && againCipher.length() <= 20)) {
                        if (!againCipher.equals(cipher)) {
                            setViewStatus(true, "两次密码不一致，请重新输入", tvAgainCipherError, etAgainCipher);
                        } else {
                            setViewStatus(false, "", tvAgainCipherError, etAgainCipher);
                        }
                    } else {
                        if (!againCipher.equals(cipher)) {
                            setViewStatus(true, "两次密码不一致，请重新输入", tvAgainCipherError, etAgainCipher);
                        } else {
                            setViewStatus(false, "", tvAgainCipherError, etAgainCipher);
                        }
                    }
                }
            }
        });
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 11) {
                    String phone = etPhone.getText().toString().trim();
                    if (TextUtils.isEmpty(phone)) {
                        setViewStatus(true, "密保手机不能为空", tvPhoneError, etPhone);
                    } else {
                        if (!RegexUtils.isMobileExact(phone)) {
                            setViewStatus(true, "请输入正确的密保手机", tvPhoneError, etPhone);
                        } else {
                            setViewStatus(false, "", tvPhoneError, etPhone);
                            mPresenter.verifyExistMobile(phone);
                        }
                    }
                }

            }
        });

        tvGetcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    setViewStatus(true, "密保手机不能为空", tvPhoneError, etPhone);
                    return;
                }
                if (!RegexUtils.isMobileExact(phone)) {
                    setViewStatus(true, "请输入正确的密保手机", tvPhoneError, etPhone);
                    return;
                }
                if (mPhoneExists) {
                    setViewStatus(true, "手机号已存在", tvPhoneError, etPhone);
                    return;
                }
                setViewStatus(false, "", tvPhoneError, etPhone);
                mPresenter.getSmsCode(phone);


            }
        });

        btnRegistered.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account = etAccount.getText().toString().trim();
                if (!(account.length() >= 5 && account.length() <= 20)) {
                    setViewStatus(true, "登录账号长度在5-20位之间", tvAccountError, etAccount);
                    return;
                } else {
                    if (mAccountExists) {
                        setViewStatus(true, "登录名已存在", tvAccountError, etAccount);
                        return;
                    } else {
                        setViewStatus(false, "", tvAccountError, etAccount);
                    }
                }

                String cipher = etCipher.getText().toString().trim();
                if (!(cipher.length() >= 5 && cipher.length() <= 20)) {
                    setViewStatus(true, "密码长度在5-20位之间", tvCipherError, etCipher);
                    return;
                } else {
                    setViewStatus(false, "", tvCipherError, etCipher);
                }

                String againCipher = etAgainCipher.getText().toString().trim();
                if (!(againCipher.length() >= 5 && againCipher.length() <= 20)) {
                    if (!againCipher.equals(cipher)) {
                        setViewStatus(true, "两次密码不一致，请重新输入", tvAgainCipherError, etAgainCipher);
                        return;
                    } else {
                        setViewStatus(false, "", tvAgainCipherError, etAgainCipher);
                    }
                } else {
                    if (!againCipher.equals(cipher)) {
                        setViewStatus(true, "两次密码不一致，请重新输入", tvAgainCipherError, etAgainCipher);
                        return;
                    } else {
                        setViewStatus(false, "", tvAgainCipherError, etAgainCipher);
                    }
                }

                String phone = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    setViewStatus(true, "密保手机不能为空", tvPhoneError, etPhone);
                    return;
                } else {
                    if (!RegexUtils.isMobileExact(phone)) {
                        setViewStatus(true, "请输入正确的密保手机", tvPhoneError, etPhone);
                        return;
                    } else {
                        if (mPhoneExists) {
                            setViewStatus(true, "手机号已存在", tvPhoneError, etPhone);
                            return;
                        } else {
                            setViewStatus(false, "", tvPhoneError, etPhone);
                        }
                    }
                }

                String code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    setViewStatus(true, "请输入验证码", tvCodeError, etCode);
                    return;
                } else {
                    setViewStatus(false, "", tvCodeError, etCode);
                }

                if (checkbox.isChecked()) {
                    mPresenter.startRegister(account, cipher, phone, code);
                } else {
                    ToastUtils.showShort("请阅读《电力市场化交易风险告知书》和 《平台使用协议》");
                }
            }
        });

        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showExitDialog();
            }
        });

        btnRealNameAuth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                ARouter.getInstance()
                        .build(AppArouterPath.APP_ASSOCIATEDENTERPRISEINFO)
                        .navigation();
            }
        });
    }

    private void showExitDialog() {
        CommonDialog commonDialog = new CommonDialog(mContext);
        commonDialog.setTitle("提示");
        commonDialog.setMessage("不关联企业信息，账户将不能使用，是否要确定要退出？");
        commonDialog.setNegtive("退出");
        commonDialog.setPositive("去关联");
        commonDialog.setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                commonDialog.dismiss();
                ARouter.getInstance()
                        .build(AppArouterPath.APP_ASSOCIATEDENTERPRISEINFO)
                        .navigation();
            }

            @Override
            public void onNegtiveClick() {
                commonDialog.dismiss();
                finish();
            }
        });
        commonDialog.show();
    }

    /**
     * 手机号码前三后四脱敏
     *
     * @param mobile 目标手机号
     * @return 脱敏手机号
     */
    public String mobileEncrypt(String mobile) {
        if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {
            return mobile;
        }
        return mobile.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
    }

    private void findViewByIds() {
        titleBar = (TitleBar) findViewById(R.id.title_bar);
        rlRegistered = (RelativeLayout) findViewById(R.id.rl_Registered);
        etAccount = (MyEditText) findViewById(R.id.et_account);
        etCipher = (MyEditText) findViewById(R.id.et_cipher);
        etAgainCipher = (MyEditText) findViewById(R.id.et_again_cipher);
        etPhone = (MyEditText) findViewById(R.id.et_phone);
        etCode = (MyEditText) findViewById(R.id.et_code);
        tvGetcode = (TextView) findViewById(R.id.tv_getcode);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        btnRegistered = (TextView) findViewById(R.id.btn_registered);
        rlRegisteredSuccess = (RelativeLayout) findViewById(R.id.rl_RegisteredSuccess);
        tvAccount = (TextView) findViewById(R.id.tv_account);
        tvPhone = (TextView) findViewById(R.id.tv_phone);
        btnRealNameAuth = (TextView) findViewById(R.id.btn_real_name_auth);
        btnExit = (TextView) findViewById(R.id.btn_exit);
        tvAccountError = (TextView) findViewById(R.id.tv_account_error);
        tvCipherError = (TextView) findViewById(R.id.tv_cipher_error);
        tvAgainCipherError = (TextView) findViewById(R.id.tv_again_cipher_error);
        tvPhoneError = (TextView) findViewById(R.id.tv_phone_error);
        tvCodeError = (TextView) findViewById(R.id.tv_code_error);
        tvPolicy = (TextView) findViewById(R.id.tv_policy);
        rlPolicy = (RelativeLayout) findViewById(R.id.rl_policy);

        ivPhoneClose = (ImageView) findViewById(R.id.iv_phone_close);

        cbCheckPwd = (CheckBox) findViewById(R.id.cb_check_pwd);
        ivPwdClose = (ImageView) findViewById(R.id.iv_pwd_close);
        etCipher.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(etCipher.getText().toString().trim())) {
                    cbCheckPwd.setVisibility(View.GONE);
                    ivPwdClose.setVisibility(View.GONE);
                } else {
                    cbCheckPwd.setVisibility(View.VISIBLE);
                    ivPwdClose.setVisibility(View.VISIBLE);
                }
            }
        });

        cbCheckPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (!isChecked) {
                    //选择状态 显示明文--设置为可见的密码
                    etCipher.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    etCipher.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });

        ivPwdClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etCipher.setText("");
            }
        });

        cbCheckAgainPwd = (CheckBox) findViewById(R.id.cb_check_again_pwd);
        ivPwdAgainClose = (ImageView) findViewById(R.id.iv_pwd_again_close);
        etAgainCipher.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(etAgainCipher.getText().toString().trim())) {
                    cbCheckAgainPwd.setVisibility(View.GONE);
                    ivPwdAgainClose.setVisibility(View.GONE);
                } else {
                    cbCheckAgainPwd.setVisibility(View.VISIBLE);
                    ivPwdAgainClose.setVisibility(View.VISIBLE);
                }
            }
        });

        cbCheckAgainPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (!isChecked) {
                    //选择状态 显示明文--设置为可见的密码
                    etAgainCipher.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    etAgainCipher.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
            }
        });

        ivPwdAgainClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etAgainCipher.setText("");
            }
        });

        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
                    ivPhoneClose.setVisibility(View.GONE);
                } else {
                    ivPhoneClose.setVisibility(View.VISIBLE);
                }
            }
        });
        ivPhoneClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                etPhone.setText("");
            }
        });

        titleBar.setTitle("注册平台账号");
        titleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });

        String str1 = "我已阅读";
        String str2 = "《电力市场化交易风险告知书》";
        String str3 = "和";
        String str4 = "《平台使用协议》";
        String str5 = "，并完全理解和同意，自愿承担电力市场交易中的各种风险引致的全部后果及损失。";

        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(str1 + str2 + str3 + str4 + str5);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                if (mMouldEditionBean != null) {
                    if (mMouldEditionBean.getData().size() >= 2) {
                        String mouldName = mMouldEditionBean.getData().get(0).getMouldName();
                        String mouldValue = mMouldEditionBean.getData().get(0).getMouldValue();
                        checkbox.setChecked(true);
                        ARouter.getInstance()
                                .build(AppArouterPath.APP_STRINGAGREEMENT)
                                .withString("title", mouldName)
                                .withString("content", mouldValue)
                                .navigation();
                    }
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#3274F0"));
                ds.setUnderlineText(false);
            }
        };
        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(@NonNull View view) {
                if (mMouldEditionBean != null) {
                    if (mMouldEditionBean.getData().size() >= 2) {
                        String mouldName = mMouldEditionBean.getData().get(1).getMouldName();
                        String mouldValue = mMouldEditionBean.getData().get(1).getMouldValue();
                        checkbox.setChecked(true);
                        ARouter.getInstance()
                                .build(AppArouterPath.APP_STRINGAGREEMENT)
                                .withString("title", mouldName)
                                .withString("content", mouldValue)
                                .navigation();
                    }
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#3274F0"));
                ds.setUnderlineText(false);
            }
        };
        spannableStringBuilder.setSpan(clickableSpan1, str1.length(), str1.length() + str2.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableStringBuilder.setSpan(clickableSpan2, str1.length() + str2.length() + str3.length(), str1.length() + str2.length() + str3.length() + str4.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        tvPolicy.setText(spannableStringBuilder);
        // 去除点击时的背景色
        tvPolicy.setHighlightColor(ContextCompat.getColor(tvPolicy.getContext(), android.R.color.transparent));
        // 点击事件生效
        tvPolicy.setMovementMethod(LinkMovementMethod.getInstance());

        tvPolicy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkbox.setChecked(!checkbox.isChecked());
            }
        });
    }

    @Override
    protected RegisteredPresenter createPresenter() {
        return new RegisteredPresenter();
    }

    @Override
    public void queryMouldEditionSuccess(MouldEditionBean response) {
        mMouldEditionBean = response;
    }

    @Override
    public void verifyExistMobileSuccess(VerifyExistMobileBean response) {
        if (response.isData()) {
            mPhoneExists = true;
            setViewStatus(true, "手机号已存在", tvPhoneError, etPhone);
        } else {
            mPhoneExists = false;
            setViewStatus(false, "", tvPhoneError, etPhone);
        }
    }

    @Override
    public void getSmsCodeSuccess(SmsCodeBean response) {
        CountDown(120);
    }

    @Override
    public void verifyExistLoginNameSuccess(VerifyExistMobileBean response) {
        if (response.isData()) {
            mAccountExists = true;
            setViewStatus(true, "登录名已存在", tvAccountError, etAccount);
        } else {
            mAccountExists = false;
            setViewStatus(false, "", tvAccountError, etAccount);
        }
    }

    /**
     * 设置是否红框显示提示文案
     *
     * @param type     true红框显示提示文案  false 不显示
     * @param message  提示文案
     * @param textView 提示文案控件
     * @param editText 红框控件
     */
    private void setViewStatus(boolean type, String message, TextView textView, EditText editText) {
        if (type) {
            textView.setText(message);
            textView.setVisibility(View.VISIBLE);
            editText.setBackgroundResource(R.drawable.bg_registered_edit_box_red);
        } else {
            textView.setVisibility(View.GONE);
            editText.setBackgroundResource(R.drawable.bg_registered_edit_box);
        }
    }

    @Override
    public void registerSuccess() {
        BurialPointUtils.onBurialPoint(BurialPointUtils.mPoint.REGISTER);
        rlRegistered.setVisibility(View.GONE);
        rlRegisteredSuccess.setVisibility(View.VISIBLE);
        titleBar.ivBack.setVisibility(View.GONE);
        String account = etAccount.getText().toString().trim();
        tvAccount.setText("登录账号：" + account);
        String phone = etPhone.getText().toString().trim();
        tvPhone.setText("密保手机：" + mobileEncrypt(phone));
    }

    @Override
    public void registerFailed() {
        DialogUtil.showConfirm(this, "提示", "系统异常,请重新登录!",
                true, new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        finish();
                    }
                });

    }

    /**
     * 倒计时
     */
    public void CountDown(int time) {
        //倒计时
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (tvGetcode != null) {
                    tvGetcode.setEnabled(false);
                    tvGetcode.setText((int) (millisUntilFinished / 1000) + "s");
                }
            }

            @Override
            public void onFinish() {
                tvGetcode.setEnabled(true);
                tvGetcode.setText("获取验证码");
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }
}
